from socket import *
from multiprocessing import Process
import re

HTML_DIR = "./html"
def fun(clientSocket):
    recvData = clientSocket.recv(1024)
    print("recvdata = ", recvData)
    recvLines = recvData.splitlines()
    requestStartLine = recvLines[0]

    fileName = re.match(r"\w+\s+(/[^ ]*)",requestStartLine.decode("utf-8")).group(1)
    if fileName == "/":
        fileName = "/index3.html"
    try:
        file = open(HTML_DIR + fileName,"rb")
        fileData = file.read()
        file.close()
    except IOError:
        responseStartLine = "HTTP/1.1 404 NOT FOUND\r\n"
        responseServer = "Server:myServer\r\n"
        responseBody = "file si not found"
    else:
        responseStartLine = "HTTP/1.1 200 OK\r\n"
        responseServer = "Server:myServer \r\n"
        responseBody = fileData.decode("utf-8")

    response = responseStartLine + responseServer + "\r\n" + responseBody
    clientSocket.send(bytes(response, 'gb2312'))
    clientSocket.close()


if __name__ == "__main__":
    serSocket = socket(AF_INET, SOCK_STREAM)
    serSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serSocket.bind(("", 7000))
    serSocket.listen(12)
    while True:
        clientSocket, clientAddr = serSocket.accept()
        print(str(clientAddr), "连上了")
        p1 = Process(target=fun, args=(clientSocket,))
        p1.start()
        clientSocket.close()
